const models = require('../db/models')

const create = async (ctx) => {

    const {name, password, email} = ctx.request.body

    if (!name) {
        ctx.body = {
            code: 1003,
            desc: '姓名不能为空'
        }
        return false
    }
    let user = await models.User.create({name, password, email})

    ctx.body = {
        code: 0,
        msg: '操作成功',
        user
    }
}

const update = async (ctx) => {

    const {id} = ctx.params
    const {name, password, email} = ctx.request.body
    if (!name) {
        ctx.body = {
            code: 1003,
            desc: '姓名不能为空'
        }
        return false
    }

    let data = await models.User.update({name, password, email},
        {where: {id}}
    )

    if(!data){
        ctx.body = {
            code: 1010,
            msg: '操作失败',
        }
    }

    ctx.body = {
        code: 0,
        msg: '修改成功'
    }
}

const list = async (ctx) => {

    let list = await models.User.findAll()

    if(!list){
        ctx.body = {
            code: 1001,
            msg: '列表数据为空',
        }
    }

    ctx.body = {
        code: 0,
        msg: '操作成功',
        list
    }
}

const get = async (ctx) => {

    let user = await models.User.findOne({
        where:{id: ctx.params.id}
    })

    if(!user){
        ctx.body = {
            code: 1001,
            msg: '数据为空',
        }
    }

    ctx.body = {
        code: 0,
        msg: '操作成功',
        user
    }
}

module.exports = {
    create,
    update,
    list,
    get
}
